﻿using System;
using System.Windows.Forms;

namespace ThreadSafeControls {
    public abstract partial class ThreadSafeControl {

        protected readonly Control _underlyingControl;
        private readonly ControlCollection _controls;

        protected ThreadSafeControl(Control control) {
            if (control == null)
                throw new ArgumentNullException("control");

            _underlyingControl = control;
            _controls = new ControlCollection(this);
        }

        internal Control UnderlyingControl {
            get { return _underlyingControl; }
        }

        public ControlCollection Controls {
            get { return _controls; }
        }

        internal void UpdateAsync(Action action) {
            if (_underlyingControl.InvokeRequired)
                _underlyingControl.BeginInvoke(action);
            else
                action();
        }

        internal T ReturnAsync<T>(Func<T> func) {
            if (_underlyingControl.InvokeRequired)
                return (T)_underlyingControl.Invoke(func);
            else
                return func();
        }

    }
}
